﻿Ext.require([
	'Ext.panel.*',
	'Ext.toolbar.*',
	'Ext.button.*',
	'Ext.container.ButtonGroup',
	'Ext.layout.container.Table'
]);

function time(seconds) {
	var h = Math.floor(seconds / 3600);
	var m = Math.floor(seconds % 3600 / 60);
	var s = Math.floor(seconds % 3600 % 60);
	return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s);
}

function loadAlbum(id) {
	store.proxy.url = Ext.String.format(apiFormat, "audio.get");
	store.proxy.extraParams.album_id = id;
	store.proxy.extraParams.count = 200;
	store.load();
}

function moveAudioToAlbum(aid, albumid) {
	var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Перемещаю в альбом…"});
	myMask.show();
	Ext.Ajax.request({
		method: "get",
	    url: Ext.String.format(apiFormat, "audio.moveToAlbum"),
	    params: {
	    	access_token: localStorage.token,
	    	aids: aid,
	    	album_id: albumid
	    },
	    success: function(response, opts) {
	        myMask.hide();
	        var obj = Ext.decode(response.responseText);
	        if (obj.response != 1) return;
	        if (localStorage.playlistType.substring(0, 5) == "album") store.load();
	    },
	    failure: function(response, opts) {
	    	myMask.hide();
	    }
	});
}

var needReact = false;
var toolbar;
var playlist;
var store;
var audioContextMenu;
var apiFormat = "https://api.vk.com/method/{0}";

var lastContextedRecord;

Ext.onReady(function() {
	if ((!localStorage.token || localStorage.expires < new Date - 0) && chrome.extension) {
		chrome.extension.getBackgroundPage().login();
	} else {
		Ext.QuickTips.init();

		audioContextMenu = new Ext.menu.Menu({
		    items: [
		    	{
		    		id: 'playmenu',
				    listeners: {
				        click: function(item) {
				        	chrome.extension.getBackgroundPage().bg.playTrack(lastContextedRecord);
				        }
				    }
		    	},
		    	{
		    		id: 'addmenu',
				    listeners: {
				        click: function(item) {
							var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Добавляю…"});
							myMask.show();
							Ext.Ajax.request({
								method: "get",
							    url: Ext.String.format(apiFormat, "audio.add"),
							    params: {
							    	access_token: localStorage.token,
							    	oid: lastContextedRecord.get("owner_id"),
							    	aid: lastContextedRecord.get("aid")
							    },
							    success: function(response, opts) {
							        myMask.hide();
							    },
							    failure: function(response, opts) {
							    	myMask.hide();
							    }
							});
				        }
				    }
		    	},
		    	{
		    		id: 'addtomenu',
		    		menu: []
		    	},
		    	{
		    		id: 'removemenu',
				    listeners: {
				        click: function(item) {
							var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Удаляю…"});
							myMask.show();
							Ext.Ajax.request({
								method: "get",
							    url: Ext.String.format(apiFormat, "audio.delete"),
							    params: {
							    	access_token: localStorage.token,
							    	oid: lastContextedRecord.get("owner_id"),
							    	aid: lastContextedRecord.get("aid")
							    },
							    success: function(response, opts) {
							        myMask.hide();
							        var obj = Ext.decode(response.responseText);
							        if (obj.response != 1) return;
/*
									for(var i = 0; i < chrome.extension.getBackgroundPage().bg.playlist.length; i++) { 
										if(chrome.extension.getBackgroundPage().bg.playlist[i] == lastContextedRecord) {
											chrome.extension.getBackgroundPage().bg.playlist.splice(i, 1);
											break;
										}
									}
							        store.loadRecords(chrome.extension.getBackgroundPage().bg.playlist);
*/
									store.load();
							    },
							    failure: function(response, opts) {
							    	myMask.hide();
							    }
							});
				        }
				    }
		    	},
		    ],
		    listeners: {
		    	beforeshow: function() {
		    		Ext.getCmp('addmenu').setDisabled(localStorage.playlistType == "myaudio");
		    		Ext.getCmp('removemenu').setDisabled(localStorage.playlistType != "myaudio");
		    		Ext.getCmp('playmenu').setText(Ext.String.format('Воспроизвести {0} - {1}', lastContextedRecord.get("artist"), lastContextedRecord.get("title")));
		    		Ext.getCmp('addmenu').setText(Ext.String.format('Добавить в мои аудиозаписи {0} - {1}', lastContextedRecord.get("artist"), lastContextedRecord.get("title")));
		    		Ext.getCmp('addtomenu').setText(Ext.String.format('Переместить {0} - {1} в альбом', lastContextedRecord.get("artist"), lastContextedRecord.get("title")));
		    		Ext.getCmp('removemenu').setText(Ext.String.format('Удалить из моих аудиозаписей {0} - {1}', lastContextedRecord.get("artist"), lastContextedRecord.get("title")));
		    		var submenu = Ext.getCmp('addtomenu').menu;
					submenu.removeAll();
					var albums = Ext.decode(localStorage.albums);
					albums.splice(0, 0, {album_id: "", title: "Основной альбом"});
					for (var i = 0; i < albums.length; i++)
						submenu.add({
							id: albums[i].album_id,
							text: albums[i].title,
							handler: function(item) {
								if (localStorage.playlistType == "myaudio" || localStorage.playlistType.substring(0, 5) == "album") moveAudioToAlbum(lastContextedRecord.get("aid"), item.id);
								else
									var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Добавляю…"});
									myMask.show();
									Ext.Ajax.request({
										method: "get",
									    url: Ext.String.format(apiFormat, "audio.add"),
									    params: {
									    	access_token: localStorage.token,
									    	oid: lastContextedRecord.get("owner_id"),
									    	aid: lastContextedRecord.get("aid")
									    },
									    success: function(response, opts) {
									        myMask.hide();
									        var obj = Ext.decode(response.responseText);
									        if (obj.response) moveAudioToAlbum(obj.response, item.id);
									    },
									    failure: function(response, opts) {
									    	myMask.hide();
									    }
									});
							}
						});
		    	}
		    }
		});

		Ext.define('Audio', {
		    extend: 'Ext.data.Model',
		    fields: [
		        {name: 'aid', type: 'string'},
		        {name: 'owner_id', type: 'string'},
		        {name: 'artist', type: 'string'},
		        {name: 'title', type: 'string'},
		        {name: 'duration', type: 'int'},
		        {name: 'url', type: 'string'}
		    ]
		});
	
		Ext.define('Album', {
		    extend: 'Ext.data.Model',
		    fields: [
		        {name: 'owner_id', type: 'string'},
		        {name: 'album_id', type: 'string'},
		        {name: 'title', type: 'string'},
		    ]
		});
	
		Ext.override(Ext.data.JsonReader, {
			read : function(response){
				var o = Ext.decode(response.responseText);
				if (o.response && typeof(o.response[0]) == 'number') o.response = o.response.slice(1);
				if (o.metaData){
					delete this.ef;
					this.meta = o.metaData;
					this.recordType = Ext.data.Record.create(o.metaData.fields);
					this.onMetaChange(this.meta, this.recordType, o);
				}
				return this.readRecords(o);
			}
		});
	
		store = Ext.create('Ext.data.Store', {
		    model: 'Audio',
		    pageSize: 200,
		    buffered: true,
		    proxy: {
		        type: 'ajax',
		        url: Ext.String.format(apiFormat, 'audio.get'),
		        reader: {
		            type: 'json',
		            root: 'response'
		        }
		    },
		    listeners: {
				beforeload: function(store, options) {
					store.proxy.extraParams.access_token = localStorage.token;
				},
				load: function(store, records, successful, operation, eOpts) {
					if (successful) {
						chrome.extension.getBackgroundPage().bg.playlist = records;
					}
				}
			}
		});
	
		toolbar = Ext.create('Ext.toolbar.Toolbar', {
			renderTo: "vkcontrols",
			width: 500,
			items: [
				{
					id: "play",
					icon: "images/play.png",
					disabled: !chrome.extension || !chrome.extension.getBackgroundPage().bg.currentTrack,
					pressed: chrome.extension && !chrome.extension.getBackgroundPage().bg.audio.paused,
					scale: "large",
					enableToggle: true,
					toggleHandler: function(button, state) {
						if (state) {
							chrome.extension.getBackgroundPage().bg.play();
						}
						else {
							chrome.extension.getBackgroundPage().bg.pause();
						}
					}
				},
				{
					id: "prev",
					icon: "images/prev.png",
					disabled: !chrome.extension || !chrome.extension.getBackgroundPage().bg.prevTrack,
					handler: function() {
						chrome.extension.getBackgroundPage().bg.prev();
					},
					scale: "large",
				},
				{
					id: "repeat",
					icon: "images/repeat.png",
					disabled: !chrome.extension || !chrome.extension.getBackgroundPage().bg.currentTrack,
					pressed: chrome.extension && chrome.extension.getBackgroundPage().bg.repeat,
					scale: "large",
					enableToggle: true,
					toggleHandler: function(button, state) {
						chrome.extension.getBackgroundPage().bg.repeat = state;
					}
				},
				{
					id: "next",
					icon: "images/next.png",
					disabled: !chrome.extension || !chrome.extension.getBackgroundPage().bg.nextTrack,
					handler: function() {
						chrome.extension.getBackgroundPage().bg.next();
					},
					scale: "large",
				},
				{
					id: "position",
					xtype: "slider",
					disabled: !chrome.extension || !chrome.extension.getBackgroundPage().bg.currentTrack,
					width: 220,
					value: chrome.extension?chrome.extension.getBackgroundPage().bg.position:0,
					increment: 1,
					minValue: 0,
					maxValue: 100,
					tipText: function(thumb){
						return time(chrome.extension.getBackgroundPage().bg.time);
					},
					listeners: {
						change: function(slider, newValue, thumb, eOpts) {
							if (needReact) {
								chrome.extension.getBackgroundPage().bg.time = chrome.extension.getBackgroundPage().bg.duration / 100.0 * newValue;
							}
						}
					}
				},
				{
					id: "volume",
					xtype: "slider",
					width: 100,
					stateId: 'volume',
					stateful: true,
					value: chrome.extension?chrome.extension.getBackgroundPage().bg.volume:0,
					increment: 1,
					minValue: 0,
					maxValue: 100,
					listeners: {
						change: function(slider, newValue, thumb, eOpts) {
							chrome.extension.getBackgroundPage().bg.volume = newValue;
						}
					}
				},
			]
		});
	
		Ext.create('Ext.toolbar.Toolbar', {
			renderTo: "vkcontrols",
			width: 500,
			items: [
				{
					id: "myaudio",
					text: "Мои аудио",
					enableToggle: true,
					toggleGroup: "playlist",
					pressed: localStorage.playlistType == "myaudio" || (localStorage.playlistType == "albumSMART" && !chrome.extension.getBackgroundPage().bg.playlist),
					toggleHandler: function(button, state) {
						if (!needReact) return;
						if (state) {
							store.proxy.url = Ext.String.format(apiFormat, "audio.get");
							localStorage.playlistType = "myaudio";
							store.proxy.extraParams.count = 200;
							delete(store.proxy.extraParams.album_id);
							store.load();
							Ext.getCmp("albumaudio").toggle(false);
						} else if (!(Ext.getCmp("myaudio").pressed || Ext.getCmp("recommendedaudio").pressed || Ext.getCmp("popularaudio").pressed || Ext.getCmp("albumaudio").pressed || Ext.getCmp("searchaudio").pressed)) button.toggle(true);
					}
				},
				{
					id: "recommendedaudio",
					text: "Рекомендации",
					stateful: true,
					enableToggle: true,
					toggleGroup: "playlist",
					pressed: localStorage.playlistType == "recommendedaudio",
					toggleHandler: function(button, state) {
						if (!needReact) return;
						if (state) {
							localStorage.playlistType = "recommendedaudio";
							store.proxy.url = Ext.String.format(apiFormat, "audio.getRecommendations");
							store.proxy.extraParams.count = 200;
							store.load();
							Ext.getCmp("albumaudio").toggle(false);
						} else if (!(Ext.getCmp("myaudio").pressed || Ext.getCmp("recommendedaudio").pressed || Ext.getCmp("popularaudio").pressed || Ext.getCmp("albumaudio").pressed || Ext.getCmp("searchaudio").pressed)) button.toggle(true);
					}
				},
				{
					id: "popularaudio",
					text: "Популярное",
					enableToggle: true,
					toggleGroup: "playlist",
					pressed: localStorage.playlistType == "popularaudio",
					toggleHandler: function(button, state) {
						if (!needReact) return;
						if (state) {
							localStorage.playlistType = "popularaudio";
							store.proxy.url = Ext.String.format(apiFormat, "audio.search");
							store.proxy.extraParams.q = "";
							store.proxy.extraParams.count = 200;
							store.load();
							Ext.getCmp("albumaudio").toggle(false);
						} else if (!(Ext.getCmp("myaudio").pressed || Ext.getCmp("recommendedaudio").pressed || Ext.getCmp("popularaudio").pressed || Ext.getCmp("albumaudio").pressed || Ext.getCmp("searchaudio").pressed)) button.toggle(true);
					}
				},
				{
					id: "albumaudio",
					text: "Альбомы",
					pressed: localStorage.playlistType && localStorage.playlistType.substring(0, 5) == "album" && (localStorage.playlistType != "albumSMART" || chrome.extension.getBackgroundPage().bg.playlist),
					menu: {
						items: [],
						listeners: {
							beforeshow: function(menu) {
								if (chrome.extension) chrome.extension.getBackgroundPage().getAlbums();
								menu.removeAll();
								var albums = Ext.decode(localStorage.albums) || [];
								for (var i = 0; i < albums.length; i++)
									menu.add({
										id: albums[i].album_id,
										text: albums[i].title,
										handler: function(item) {
											localStorage.playlistType = "album" + item.id;
											loadAlbum(item.id);
											needReact = false;
											Ext.getCmp("myaudio").toggle(false);
											Ext.getCmp("recommendedaudio").toggle(false);
											Ext.getCmp("popularaudio").toggle(false);
											Ext.getCmp("searchaudio").toggle(false);
											Ext.getCmp("albumaudio").toggle(true);
											needReact = true;
										}
									});
								menu.add([
								"-",
								{
									text: "Умный поиск",
									handler: function(item) {
										ssWindow.show();
									}
								}]);
							},
						}
					},
				},
				{
					id: "query",
					xtype: "textfield",
					width: 144,
					value: localStorage.query,
					plugins: ['clearbutton'],
					listeners: {
						specialkey: function(field, e) {
							if (e.getKey() == e.ENTER) {
								Ext.getCmp("searchaudio").toggle(true);
							}
						},
						change: function(tf, newValue) {
							localStorage.query = newValue;
						}
					},
					emptyText: "найти…",
				},
				{
					id: "searchaudio",
					text: "Поиск",
					enableToggle: true,
					toggleGroup: "playlist",
					pressed: localStorage.playlistType == "searchaudio",
					toggleHandler: function(button, state) {
						if (!needReact) return;
						if (state) {
							localStorage.playlistType = "searchaudio";
							store.proxy.url = Ext.String.format(apiFormat, "audio.search");
							store.proxy.extraParams.q = Ext.getCmp("query").value;
							store.proxy.extraParams.count = 200;
							store.load();
							Ext.getCmp("albumaudio").toggle(false);
						} else if (!(Ext.getCmp("myaudio").pressed || Ext.getCmp("recommendedaudio").pressed || Ext.getCmp("popularaudio").pressed || Ext.getCmp("albumaudio").pressed || Ext.getCmp("searchaudio").pressed)) button.toggle(true);
					}
				},
			]
		});
	
		playlist = Ext.create('Ext.grid.Panel', {
			collapsible: true,
			collapsed: localStorage.collapsed,
			store: store,
			stateful: false,
			listeners: {
				itemdblclick: function(t, record, item, index, e, eOpts) {
					chrome.extension.getBackgroundPage().bg.playTrack(record);
				},
				itemcontextmenu: function(grid, record, item, index, e, eOpts) {
					e.stopEvent();
					lastContextedRecord = record;
					audioContextMenu.showAt(e.xy);
				},
				viewready: function(grid) {
					if (chrome.extension && chrome.extension.getBackgroundPage().bg.currentTrack) {
						playlist.getSelectionModel().select(chrome.extension.getBackgroundPage().bg.currentTrack);
						//chrome.extension.getBackgroundPage().bg.currentTrack.current = true;
					}
					needReact = true;
					if (chrome.extension && chrome.extension.getBackgroundPage().bg.playlist) store.loadRecords(chrome.extension.getBackgroundPage().bg.playlist);
					else {
						if (localStorage.playlistType && localStorage.playlistType.substring(0, 5) == "album") {
							if (localStorage.playlistType == "albumSMART") {
								localStorage.playlistType = "myaudio";
								Ext.getCmp("myaudio").pressed = false;
								Ext.getCmp("myaudio").toggle(true);
							} else {
								var id = localStorage.playlistType.substring(5);
								loadAlbum(id);
							}
						} else {
							Ext.getCmp(localStorage.playlistType || "myaudio").pressed = false;
							Ext.getCmp(localStorage.playlistType || "myaudio").toggle(true);
						}
					}
				},
				collapse: function() {
					localStorage.collapsed = 1;
				},
				expand: function() {
					localStorage.removeItem("collapsed");
				}
			},
			columns: [
				{
					xtype: 'rownumberer',
					align: 'right',
					width: 30
				},
				{
					text: 'aid',
					hidden: true,
					dataIndex: 'aid'
				},
				{
					text: 'owner',
					hidden: true,
					dataIndex: 'owner_id'
				},
				{
					text: 'Исполнитель',
					flex: 1,
					menuDisabled: true,
					sortable: false,
					dataIndex: 'artist'
				},
				{
					text: 'Композиция',
					flex: 1,
					menuDisabled: true,
					sortable: false,
					dataIndex: 'title'
				},
				{
					text: 'Время',
					align: 'center',
					width: 60,
					resizable: false,
					menuDisabled: true,
					sortable: false,
					renderer: time,
					dataIndex: 'duration'
				},
				{
					resizable: false,
					align: 'center',
					menuDisabled: true,
					sortable: false,
					width: 30,
					renderer: function(value, metaData, record) {
						return '<a href="' + record.get("url") + '" class="downButton" title="Для скачивания перетащите в папку или кликните" download="' + record.get("artist") + ' - ' + record.get("title") + '" draggable="true" data-downloadurl="audio/mpeg:' + record.get("artist") + ' - ' + record.get("title") + ':' + record.get("url") + '" class="download"><img src="download.gif" /></a>';
					}
				}
			],
			height: 300,
			width: 500,
			title: chrome.extension?chrome.extension.getBackgroundPage().bg.currentTrackName:'',
			renderTo: "vkcontrols",
			viewConfig: {
				stripeRows: true,
			    getRowClass: function(record, index, rowParams, store) {
					if (record.current) {
						return 'currentPlaying';
					} else {
						return '';
					}
				}
			}
		});
	}
});
